<template>
  <div class="order-list">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="item in orderStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单类型">
          <el-select v-model="searchForm.orderType" placeholder="请选择类型" clearable>
            <el-option
              v-for="item in orderTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表区域 -->
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span>订单列表</span>
            <el-tag type="warning" v-if="selectedOrders.length">
              已选择 {{ selectedOrders.length }} 项
            </el-tag>
          </div>
          <div class="header-right">
            <el-button type="primary" @click="handleBatchShip" :disabled="!selectedOrders.length">
              批量发货
            </el-button>
            <el-button type="danger" @click="handleBatchCancel" :disabled="!selectedOrders.length">
              批量取消
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="orderNo" label="订单编号" width="180" />
        <el-table-column prop="orderType" label="订单类型" width="120">
          <template #default="{ row }">
            <el-tag :type="row.orderType === 'package' ? 'success' : 'info'">
              {{ getOrderTypeText(row.orderType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单时间" width="180" />
        <el-table-column prop="customerName" label="客户名称" min-width="120" />
        <el-table-column prop="amount" label="订单金额" width="120">
          <template #default="{ row }">
            <span class="amount">¥ {{ row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getOrderStatusType(row.status)">
              {{ getOrderStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleDetail(row)">详情</el-button>
            <el-button 
              v-if="row.status === 'pending'" 
              link 
              type="primary" 
              @click="handleShip(row)"
            >
              发货
            </el-button>
            <el-button 
              v-if="row.status === 'pending'" 
              link 
              type="danger" 
              @click="handleCancel(row)"
            >
              取消
            </el-button>
            <el-button 
              v-if="row.status === 'completed'" 
              link 
              type="warning" 
              @click="handleAfterSale(row)"
            >
              售后
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      :title="currentOrder.orderType === 'package' ? '套餐订单详情' : '订单详情'"
      size="60%"
      destroy-on-close
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ currentOrder.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="订单类型">
          <el-tag :type="currentOrder.orderType === 'package' ? 'success' : 'info'">
            {{ getOrderTypeText(currentOrder.orderType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ currentOrder.createTime }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ currentOrder.customerName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentOrder.phone }}</el-descriptions-item>
        <el-descriptions-item label="收货地址">{{ currentOrder.address }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">¥ {{ currentOrder.amount }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getOrderStatusType(currentOrder.status)">
            {{ getOrderStatusText(currentOrder.status) }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 套餐信息 -->
      <template v-if="currentOrder.orderType === 'package'">
        <el-divider>套餐信息</el-divider>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="套餐名称">{{ currentOrder.package?.name }}</el-descriptions-item>
          <el-descriptions-item label="套餐描述">{{ currentOrder.package?.description }}</el-descriptions-item>
          <el-descriptions-item label="原价">¥ {{ currentOrder.package?.originalPrice }}</el-descriptions-item>
          <el-descriptions-item label="优惠价">¥ {{ currentOrder.package?.discountPrice }}</el-descriptions-item>
          <el-descriptions-item label="优惠说明">{{ currentOrder.package?.discountDesc }}</el-descriptions-item>
        </el-descriptions>
      </template>

      <el-divider>商品清单</el-divider>
      
      <el-table :data="currentOrder.items" border>
        <el-table-column prop="name" label="商品名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="specs" label="规格" width="120" show-overflow-tooltip />
        <el-table-column prop="price" label="单价" width="120">
          <template #default="{ row }">
            <span :class="{ 'discount-price': currentOrder.orderType === 'package' }">
              ¥ {{ row.price }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="100" align="center" />
        <el-table-column label="小计" width="120">
          <template #default="{ row }">
            <span :class="{ 'discount-price': currentOrder.orderType === 'package' }">
              ¥ {{ row.price * row.quantity }}
            </span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 套餐优惠信息 -->
      <template v-if="currentOrder.orderType === 'package'">
        <div class="package-summary">
          <div class="summary-item">
            <span>商品总价</span>
            <span class="original-price">¥ {{ currentOrder.package?.originalPrice }}</span>
          </div>
          <div class="summary-item">
            <span>套餐优惠</span>
            <span class="discount">
              -¥ {{ currentOrder.package?.originalPrice - currentOrder.package?.discountPrice }}
            </span>
          </div>
          <div class="summary-item total">
            <span>实付金额</span>
            <span class="final-price">¥ {{ currentOrder.package?.discountPrice }}</span>
          </div>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'

// 搜索表单
const searchForm = ref({
  orderNo: '',
  status: '',
  orderType: '',
  dateRange: []
})

// 表格相关
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedOrders = ref([])

// 抽屉相关
const drawerVisible = ref(false)
const currentOrder = ref({
  orderNo: '',
  orderType: '',
  createTime: '',
  customerName: '',
  phone: '',
  address: '',
  amount: 0,
  status: '',
  items: []
})

// 订单状态选项
const orderStatusOptions = [
  { value: 'pending', label: '待发货' },
  { value: 'shipping', label: '配送中' },
  { value: 'completed', label: '已完成' },
  { value: 'cancelled', label: '已取消' },
  { value: 'refunding', label: '退款中' }
]

// 订单类型选项
const orderTypeOptions = [
  { value: 'normal', label: '普通订单' },
  { value: 'package', label: '套餐订单' }
]

// 模拟数据
const tableData = ref([
  {
    orderNo: 'DD20231128001',
    orderType: 'normal',
    createTime: '2023-11-28 10:00:00',
    customerName: '张三',
    phone: '13800138000',
    address: '北京市朝阳区xxx街道',
    amount: 2999,
    status: 'pending',
    items: [
      { name: '现代简约沙发', specs: '三人位', price: 2999, quantity: 1 }
    ]
  },
  {
    orderNo: 'DD20231128002',
    orderType: 'package',
    createTime: '2023-11-28 11:00:00',
    customerName: '李四',
    phone: '13900139000',
    address: '北京市海淀区xxx街道',
    amount: 8999,
    status: 'pending',
    package: {
      name: '现代简约客厅套餐',
      description: '包含沙发、茶几、电视柜等全套客厅家具',
      originalPrice: 12999,
      discountPrice: 8999,
      discountDesc: '套餐优惠4000元'
    },
    items: [
      { name: '现代简约沙发', specs: '三人位', price: 5999, quantity: 1 },
      { name: '现代简约茶几', specs: '1.2米', price: 2999, quantity: 1 },
      { name: '现代简约电视柜', specs: '2.4米', price: 4001, quantity: 1 }
    ]
  }
])

// 方法
const getOrderStatusType = (status: string) => {
  const map: Record<string, string> = {
    pending: 'warning',
    shipping: 'primary',
    completed: 'success',
    cancelled: 'info',
    refunding: 'danger'
  }
  return map[status] || 'info'
}

const getOrderStatusText = (status: string) => {
  const map: Record<string, string> = {
    pending: '待发货',
    shipping: '配送中',
    completed: '已完成',
    cancelled: '已取消',
    refunding: '退款中'
  }
  return map[status] || '未知状态'
}

const getOrderTypeText = (type: string) => {
  return type === 'package' ? '套餐订单' : '普通订单'
}

const handleSearch = () => {
  currentPage.value = 1
  loadData()
}

const resetSearch = () => {
  searchForm.value = {
    orderNo: '',
    status: '',
    orderType: '',
    dateRange: []
  }
  handleSearch()
}

const loadData = async () => {
  loading.value = true
  try {
    // 这里调用接口获取数据
    total.value = tableData.value.length
  } catch (error) {
    console.error('加载数据失败：', error)
  } finally {
    loading.value = false
  }
}

const handleDetail = (row: any) => {
  currentOrder.value = { ...row }
  drawerVisible.value = true
}

const handleShip = async (row: any) => {
  try {
    await ElMessageBox.confirm('确认发货该订单？')
    ElMessage.success('发货成功')
    loadData()
  } catch {}
}

const handleCancel = async (row: any) => {
  try {
    await ElMessageBox.confirm('确认取消该订单？', '提示', {
      type: 'warning'
    })
    ElMessage.success('订单已取消')
    loadData()
  } catch {}
}

const handleAfterSale = (row: any) => {
  // 跳转到售后页面
}

const handleSelectionChange = (val: any[]) => {
  selectedOrders.value = val
}

const handleBatchShip = async () => {
  try {
    await ElMessageBox.confirm(`确认批量发货 ${selectedOrders.value.length} 个订单？`)
    ElMessage.success('批量发货成功')
    loadData()
  } catch {}
}

const handleBatchCancel = async () => {
  try {
    await ElMessageBox.confirm(`确认批量取消 ${selectedOrders.value.length} 个订单？`, '提示', {
      type: 'warning'
    })
    ElMessage.success('批量取消成功')
    loadData()
  } catch {}
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadData()
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.order-list {
  .search-card {
    margin-bottom: 20px;
    
    .search-form {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      
      .el-form-item {
        margin-bottom: 0;
        margin-right: 0;
      }
    }
  }
  
  .list-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-left {
        display: flex;
        align-items: center;
        gap: 10px;
      }
    }
    
    .amount {
      color: #f56c6c;
      font-weight: bold;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

// 响应式处理
@media screen and (max-width: 768px) {
  .order-list {
    .search-form {
      .el-form-item {
        width: 100%;
      }
    }
  }
}

.package-summary {
  margin-top: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;

  .summary-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    &.total {
      margin-top: 12px;
      padding-top: 12px;
      border-top: 1px solid #dcdfe6;
      font-weight: bold;
    }
    
    .original-price {
      color: #909399;
      text-decoration: line-through;
    }
    
    .discount {
      color: #67c23a;
    }
    
    .final-price {
      color: #f56c6c;
      font-size: 18px;
    }
  }
}

.discount-price {
  color: #909399;
  text-decoration: line-through;
}
</style> 